package com.hnust.root.common.util;

import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.util.Date;

/**
 * @Author zhusir
 * @Date 2019/1/26
 * @Desc
 */
public class ComUtil {

    private static final Log LOGGER = LogFactory.get();

    private static final ObjectMapper JACKSON_OBJ_MAPPER = new ObjectMapper()
            .registerModule(new JavaTimeModule())
            .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
            .setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE)                   // 下划线转驼峰
            .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)       // 忽略不在类中的Json属性
            .setSerializationInclusion(JsonInclude.Include.ALWAYS);

    /**
     * 从json字符串中解析得到指定的类.
     * @param json json字符串
     * @param cls 需要解析成的对象
     * @param <T> 对象类型
     * @return 解析成的对象
     */
    public static <T> T fromJson(String json, Class<T> cls) {
        try {
            return JACKSON_OBJ_MAPPER.readValue(json, cls);
        } catch (IOException e) {
            LOGGER.error("从json解析对象失败！", e);
        }
        return null;
    }

    /**
     * 将对象转换成字符串.
     * @param object 需要转换成json的对象
     * @return json字符串
     */
    public static String toJson(Object object) {
        String result = null;
        try {
            result = JACKSON_OBJ_MAPPER.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            LOGGER.error("转换成json字符串失败！", e);
        }
        return result;
    }
    /**
     * 获取当前请求.
     * @return 当前请求
     */
    public static HttpServletRequest getCurRequest() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }

    /**
     * 对localdatetime和date进行互转
     * @param date
     * @return
     */
    public static LocalDateTime date2LocalDateTime(Date date) {
        if(null == date) {
            return null;
        }
        return LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
    }

    public static Date localDateTime2Date(LocalDateTime localDateTime) {
        if(null == localDateTime) {
            return null;
        }
        ZonedDateTime zonedDateTime = localDateTime.atZone(ZoneId.systemDefault());
        return Date.from(zonedDateTime.toInstant());
    }

    public static Long datetimeToTimestamp(LocalDateTime dateTime) {
        return dateTime.toInstant(ZoneOffset.of("+8")).toEpochMilli();
    }

    public static LocalDateTime timestampToLocalDate(Long timestamp) {
        return LocalDateTime.ofEpochSecond(timestamp / 1000, 0, ZoneOffset.ofHours(8));
    }

    //数据库操作是否成功
    public static boolean DBisSuccess(int result) {
        return result !=0;
    }
}
